package com.wt.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wt.admin.entity.WqunArticleTag;
import com.wt.admin.entity.WqunArticleTagType;
import com.wt.admin.mapper.WqunArticleTagMapper;
import com.wt.admin.mapper.WqunArticleTagTypeMapper;
import com.wt.admin.service.WqunArticleTagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wt.commonutils.R;
import com.wt.servicebase.exceptionhandler.exceptionhandler.WQUNException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 标签表 服务实现类
 * </p>
 *
 * @author wt
 * @since 2023-10-13
 */
@Service
public class WqunArticleTagServiceImpl extends ServiceImpl<WqunArticleTagMapper, WqunArticleTag> implements WqunArticleTagService {

    @Autowired
    public WqunArticleTagTypeMapper wqunArticleTagTypeMapper;

    @Override
    public R addArticleTag(WqunArticleTag wqunArticleTag) {
        if(wqunArticleTag.getName().isEmpty()){
            throw new WQUNException(20004,"标签名不能为空");
        }
        if(wqunArticleTag.getName().length() > 15){
            throw new WQUNException(20004,"标签名长度不能超过15");
        }
        if(wqunArticleTag.getTypeId().isEmpty()){
            throw new WQUNException(20001,"标签类型查找异常，请重试");
        }
        int insert = baseMapper.insert(wqunArticleTag);
        if(insert > 0){
            return R.ok().message("添加成功");
        }else{
            throw new WQUNException(20003,"添加失败");
        }
    }

    @Override
    public R findAllArticleTag(int pageSize, int currentPage, String selectFind, String selectFindValue) {
        IPage<WqunArticleTag> resultPage = new Page<>(currentPage,pageSize);
        QueryWrapper<WqunArticleTag> queryWrapper = new QueryWrapper<>();
        if(!Objects.equals(selectFind, "NULL") && !Objects.equals(selectFindValue, "NULL")){
            queryWrapper.like(true,selectFind,selectFindValue);
        }
//        queryWrapper.orderByDesc("id");
        queryWrapper.eq("is_delete","0");
        IPage<WqunArticleTag> iPage = baseMapper.selectPage(resultPage, queryWrapper);
        List<WqunArticleTag> findAllArticleTag = iPage.getRecords();
        for (int i = 0; i < findAllArticleTag.size(); i++) {
            WqunArticleTag wqunArticleTag = findAllArticleTag.get(i);
            WqunArticleTagType wqunArticleTagType = wqunArticleTagTypeMapper.selectById(wqunArticleTag.getTypeId());
            wqunArticleTag.setTypeId(wqunArticleTagType.getName());
            findAllArticleTag.set(i,wqunArticleTag);
        }
        long total = iPage.getTotal();

        return R.ok().data("findAllArticleTag",findAllArticleTag).data("total",baseMapper.selectPage(resultPage, queryWrapper).getTotal());

    }
}
